<?php

namespace app\admin\controller\talent;

use app\common\controller\Backend;
use app\common\library\TencentIm;
use fast\Http;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class TalentGoodsOrders extends Backend
{

    /**
     * TalentGoodsOrders模型对象
     * @var \app\admin\model\talent\TalentGoodsOrders
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\talent\TalentGoodsOrders;
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	/**
	 * 查看
	 *
	 * @return string|Json
	 * @throws \think\Exception
	 * @throws DbException
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if (false === $this->request->isAjax()) {
			return $this->view->fetch();
		}
		//如果发送的来源是 Selectpage，则转发到 Selectpage
		if ($this->request->request('keyField')) {
			return $this->selectpage();
		}
		[$where, $sort, $order, $offset, $limit] = $this->buildparams();
		$list = $this->model
			->with(['users','goods','service_user'])
			->where($where)
			->order($sort, $order)
			->paginate($limit);
		$result = ['total' => $list->total(), 'rows' => $list->items()];
		return json($result);
	}
	
	/**
	 * 编辑
	 *
	 * @param $ids
	 * @return string
	 * @throws DbException
	 * @throws \think\Exception
	 */
	public function edit($ids = null)
	{
		$row = $this->model->get($ids);
	
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$adminIds = $this->getDataLimitAdminIds();
		if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
			$this->error(__('You have no permission'));
		}
		if (false === $this->request->isPost()) {
			$this->view->assign('row', $row);
			if ($row->pay_status==3){
				$this->view->assign("payStatusList", ['1' => __('Pay_status 1'), '3' => __('Pay_status 3')]);
			}else{
				$this->view->assign("payStatusList", [ $row->pay_status=>__("Pay_status $row->pay_status")]);
			}
			return $this->view->fetch();
		}
		$params = $this->request->post('row/a');
		if (empty($params)) {
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$params = $this->preExcludeFields($params);
		$result = false;
		Db::startTrans();
		try {
			//是否采用模型验证
			if ($this->modelValidate) {
				$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
				$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
				$row->validateFailException()->validate($validate);
			}
			
			if ($row->pay_status==3&&$params['pay_status']==1){
				
				$service_user_id = $params['service_user_id'];
				if (empty($service_user_id)){
					throw new Exception('请选择服务人员');
				}
				$service = $this->model->where(['service_user_id'=>$service_user_id,'pay_status'=>1])->find();
				if ($service){
					throw new Exception('此客服正在服务中');
				}
				
				$time=time();
				$sku_json = json_decode($row->sku_json);
				$ret=json_decode(TencentIm::getInstance()->send_msg($params['service_user_id'],$row->users_id,[['MsgType'=>'TIMTextElem','MsgContent'=>['Text'=>'你好，有什么可以帮到你?']]]));
				if ($ret->ErrorCode!=0){
					throw new Exception('发送消息失败');
				}
				$res = Http::get(config('site.api_host').'/Config/add_queue',[
					'data'=>['data' => ['id' => $row->id], 'action' => 'TalentGoodsServiceOver'],
					'expiretime'=>$sku_json->minutes*60
				]);
				$res = json_decode($res);
				if ($res->code!=1){
					throw new Exception($res->msg);
				}
				$params['expiretime'] =$time+$sku_json->minutes*60;
			}
			
			$result = $row->allowField(true)->save($params);
			Db::commit();
		} catch (ValidateException|PDOException|Exception $e) {
			Db::rollback();
			$this->error($e->getMessage());
		}
		if (false === $result) {
			$this->error(__('No rows were updated'));
		}
		$this->success();
	}


}
